package com.tueye.utils;

import org.apache.log4j.Logger;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.FileSystemResource;
import org.springframework.web.context.WebApplicationContext;

/**
 * 加载的文件为applicationContext.xml 此类还提供用户权限信息的存储与检索
 * 
 * @author hanxiaowei
 * 
 */
public class ServiceLocator {
	private static final Logger logger = Logger.getLogger(ServiceLocator.class);

	private static ServiceLocator locator = null;

	private static XmlBeanFactory factory = null;

	private static String currentEnv = "webEnv";

	private static WebApplicationContext webApplicationContext = null;

	public static synchronized ServiceLocator getInstance() {
		if (locator == null) {
			locator = new ServiceLocator();
		}
		if (webApplicationContext == null) {
			initFactory();
		}
		return locator;
	}

	private static void initFactory() {
		try {
			if (TuEyeConstant.systemPath == null)
				TuEyeConstant.setSystemPath(AppHelper.getWebAppPath());
			factory = new XmlBeanFactory(
					new FileSystemResource(
							TuEyeConstant.systemPath
									+ "//WEB-INF//resources//spring//applicationContext.xml"));
			PropertyPlaceholderConfigurer cfg = new PropertyPlaceholderConfigurer();
			cfg.setLocation(new FileSystemResource(TuEyeConstant.systemPath
					+ "//WEB-INF//resources//spring//spring.properties"));
			cfg.postProcessBeanFactory(factory);
		} catch (BeansException ex) {
			locator = null;
			logger.error(ex.getMessage());
		}
	}

	public static void setEnv(String envParam) {
		currentEnv = envParam;
	}

	/**
	 * the common method of getting service
	 * 
	 * @param name
	 * @return
	 */
	public Object getService(String name) {
		if (webApplicationContext != null) {
			logger.info("从Spring的WebApplicationContext获取Bean实例，实例名称为：" + name);
			return webApplicationContext.getBean(name);
		} else {
			logger.info("从Spring的XmlBeanFactory获取Bean实例，实例名称为：" + name);
			return factory.getBean(name);
		}
	}
	
	public static void setWebApplicationContext(
			WebApplicationContext webApplicationContext) {
		logger.info("从Web容器中加载当前的Spring上下文到ServiceLocator....");
		ServiceLocator.webApplicationContext = webApplicationContext;
	}

}
